package com.ruoyi.business.service.distributed;

import com.ruoyi.business.utils.lock.DistributedLockFactory;
import com.ruoyi.business.utils.lock.DistributedRedisLock;
import com.ruoyi.common.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class StockService {

    @Autowired
    private RedisService redisService;

    @Autowired
    private DistributedLockFactory distributedLockFactory;


    public void deduct(){
        DistributedRedisLock lock = distributedLockFactory.getRedisLock("lock");
        lock.lock();
        try {
            // 查询库存信息
            String stock = redisService.getCacheObject("stock").toString();

            // 判断库存是否充足
            if (stock!=null && stock.length()!=0){
                Integer st = Integer.valueOf(stock);
                if (st > 0){
                    // 扣减库存
                    redisService.setCacheObject("stock",String.valueOf(--st));
                }
            }
            // test();
        } finally {
            lock.unlock();
        }
        System.out.println("扣减成功");
    }

    public void test(){
        DistributedRedisLock lock = distributedLockFactory.getRedisLock("lock");
        lock.lock();
        System.out.println("测试重入......");
        lock.unlock();
    }
}
